<template>
  <layout-page :size="6">
    <scroll-view class="flex-1" :scroll-y="true" style="height: 100vh">
      <template #default>
        <van-sidebar :active-key="activeIndex">
          <van-sidebar-item
            v-for="(item, index) in sidebarItems"
            :key="index"
            @click="changeActive(item.id, index)"
          >
            <template #title>
              <text :class="{ title: activeId === item.id }"
                >{{ item.title }}
              </text>
            </template>
          </van-sidebar-item>
        </van-sidebar>
      </template>
    </scroll-view>
    <template #show>
      <cell-page>
        <template #title>
          <topic-components
            :tableData="tableData"
            :loading="loading"
            :hasMore="hasMore"
            @loadMore="loadMore"
          ></topic-components>
        </template>
      </cell-page>
    </template>
  </layout-page>
</template>

<script setup lang="ts">
import LayoutPage from '@/layout/LayoutPage.vue'
import { ref, onMounted } from 'vue'
import { getCategoryList } from '@/api/topic'
import type { CategoryTypeData } from '@/common/topic/topicType'
import CellPage from '@/layout/CellPage.vue'
import { onReady } from '@dcloudio/uni-app'
import TopicComponents from '@/layout/PageItemComponents/topicComponents.vue'
import { loadDataCommon } from '@/common/loadData'

const { loading, hasMore, tableData, page, loadData, activeId, position } =
  loadDataCommon()
// 侧边栏数据
const sidebarItems = ref<CategoryTypeData[]>([])
const type = ref('topic')
onMounted(() => {
  getCategoryList(type.value).then((res) => {
    sidebarItems.value = res.data.map((item, index) => {
      // 第一个默认选中
      if (index === 0) {
        changeActive(item.id, index)
      }
      return item
    })
  })
})
// 切换侧边栏

//设置当前激活的标签索引
const activeIndex = ref(0)
const changeActive = (id: number, index: number) => {
  activeId.value = id
  activeIndex.value = index
  page.value = 1
  hasMore.value = false
  tableData.value.length = 0
  loadData()
}
// 是否加载指定分类下的话题列表

// 加载更多
const loadMore = () => {
  // 数据未到底部，加载更多
  if (hasMore.value == true) return
  loadData()
}
onReady(() => {
  position.value = 'topic'
})
</script>
<script lang="ts">
export default {
  name: 'TopicComponent'
}
</script>

<style scoped>
.title {
  @apply text-red-500;
}
</style>
